package com.easy.sso.service.impl;
import com.easy.common.exception.ExceptionEnum;
import com.easy.common.util.Result;
import com.easy.common.util.Tools;
import com.easy.sso.dto.User;
import com.easy.sso.exception.LoginException;
import com.easy.sso.mapper.UserMapper;
import com.easy.sso.service.LoginService;
import com.easy.sso.util.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: CoolPro
 * @Description:
 * @Time: 2024-04-19 19:25
 **/
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Result login(User user) {
        List<User> users = userMapper.loginCheck(user);
        if (users.size() > 0) {
            //根据用户名密码生成token
            String token = JwtUtil.generateToken(user.getAccount());
//            stringRedisTemplate.expire(token, 60 , TimeUnit.SECONDS);
            Map<String,Object> map = new HashMap<>();
            map.put("user",users.get(0));
            map.put("token",token);
            return Result.success(map);
        }
        throw new LoginException(ExceptionEnum.NOT_FIND_USER);
    }

    @Override
    public Result<String> register(User user) {
        if(checkUserExist(user)){
            return Result.error(ExceptionEnum.USER_ALREADY_EXISTS);
        }
        userMapper.addUser(user);
        return Result.success();
    }

    public boolean checkUserExist(User user) {
        return userMapper.findUserByAccount(user).size() > 0;
    }
}
